<template>
    <div class="madp-chanel-statistics">
        <div class="madp-statistics-data" v-show="!isStatisticsCstDetailShow">
            <div class="madp-channel-name">渠道码:{{ codeName }}</div>
            <div class="madp-top-statistics-boxs">
                <statistics-card :cardInfo="cardInfo" :cardData="basicCstNumInfo" />
            </div>
            <div class="madp-horizontal-divider"></div>
            <div class="madp-gap-wrap">
                <div class="madp-gap-title">图表数据</div>
                <div class="madp-statistics-tabs">
                    <div class="madp-statistics-tabs-left">
                        <el-button-group>
                            <el-button :type="dimensionType === item.value ? 'primary' : ''" v-for="item in statisticDimensionTypes" :key="item.value" @click="selectDimensionType(item)">{{
                                item.label
                            }}</el-button>
                        </el-button-group>
                        <el-popover placement="bottom-start" width="400" trigger="hover">
                            <div>
                                <p>1、客户总数:扫码添加的客户总数，若客户重复添加将不会重复计数</p>
                                <p>2、新增客户数:扫码添加的新增客户数，包含流失数据</p>
                                <p>3、流失客户数:扫码添加后将成员删除的客户数</p>
                            </div>
                            <el-button type="text" slot="reference" style="margin-left: 20px">
                                统计说明
                                <i class="el-icon-question"></i>
                            </el-button>
                        </el-popover>
                    </div>
                </div>
                <div class="madp-date-picker-wrap madp-statistics-tabs">
                    <div class="madp-statistics-tabs-left">
                        <el-form :inline="true" class="madp-chart-form">
                            <el-form-item>
                                <el-select class="madp-date-select" v-model="dateType" placeholder="请选择">
                                    <el-option v-for="item in dateTypes" :key="item.type" :label="item.label" :value="item.type"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="自定义:">
                                <el-date-picker
                                    v-model="dateRangeVal"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :picker-options="{
                                        disabledDate(time) {
                                            return time.getTime() > Date.now();
                                        }
                                    }"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    @change="resetDateType"
                                ></el-date-picker>
                            </el-form-item>
                            <el-form-item label="请选择员工:">
                                <el-select v-model="employeeId" placeholder="请选择员工" filterable @change="() => queryDataByParamsChange()">
                                    <el-option v-for="item in employeeList" :key="item.employeeId" :label="item.name" :value="item.employeeId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                    <el-button plain @click="resetQuery">重置</el-button>
                </div>
                <!-- 折线图 -->
                <div id="lineChart" style="width: 100%; height: 400px; margin: 30px auto"></div>
            </div>
            <div class="madp-horizontal-divider"></div>
            <div class="madp-gap-wrap">
                <div class="madp-gap-title">表格数据</div>
                <div class="madp-statistics-tabs">
                    <el-button-group>
                        <el-button :type="tableType === 'date' ? 'primary' : ''" @click="getTableData('date')">按日期查看</el-button>
                        <el-button :type="tableType === 'staff' ? 'primary' : ''" @click="getTableData('staff')">按员工查看</el-button>
                    </el-button-group>
                    <download-btn title="导出Excel" @click="downloadExcel" />
                </div>
                <div class="madp-statistics-table" v-if="tableType === 'date'">
                    <el-table
                        :header-cell-style="{
                            background: 'rgb(255, 191, 191)',
                            color: 'rgb(44,44,44)'
                        }"
                        stripe
                        :data="statisticsTableData"
                    >
                        <el-table-column prop="createTime" label="日期" width="150" align="center"></el-table-column>
                        <el-table-column prop="allAddContact" label="客户总数" width="200" align="center"></el-table-column>
                        <el-table-column prop="newAddContact" label="新增人数" align="center"></el-table-column>
                        <el-table-column prop="newLossContact" label="流失人数" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" @click="showDetail(scope.row)">查看详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="madp-statistics-table" v-else>
                    <el-table
                        :header-cell-style="{
                            background: 'rgb(255, 191, 191)',
                            color: 'rgb(44,44,44)'
                        }"
                        stripe
                        :data="statisticsTableData"
                    >
                        <el-table-column prop="name" label="员工名称" width="150" align="center"></el-table-column>
                        <el-table-column prop="allAddContact" label="客户总数" width="200" align="center"></el-table-column>
                        <el-table-column prop="newAddContact" label="新增人数" align="center"></el-table-column>
                        <el-table-column prop="allLossContact" label="流失人数" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" @click="showDetail(scope.row)">查看详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="madp-bottom-pagination">
                    <el-pagination
                        background
                        :current-page="page.current"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :page-sizes="[10, 20, 30, 50, 100]"
                        :page-size="page.size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="page.total"
                        style="float: right"
                    ></el-pagination>
                </div>
            </div>
        </div>
        <div v-if="!isStatisticsCstDetailShow">
            <el-dialog title="查看详情" :close-on-click-modal="false" :visible.sync="detailVisible" @close="onCloseDetail" width="1000px">
                <div class="madp-detail">
                    <div class="madp-detail-btn">
                        <el-button-group>
                            <el-button
                                :type="dimensionDialogType === item.value ? 'primary' : ''"
                                v-for="item in statisticDimensionTypes"
                                :key="item.value"
                                @click="
                                    dimensionDialogType = item.value;
                                    showDetail(selectedRow, item.value);
                                "
                                >{{ item.label }}</el-button
                            >
                        </el-button-group>
                        <span class="madp-detail-btn-desc">管理权限范围不同，展示的客户详情数据也不同哦～</span>
                    </div>
                    <div class="madp-detail-basic">
                        <div class="madp-detail-basic-info">
                            <div class="madp-detail-basic-info-num">共{{ detailPage.total }}个客户</div>
                            <div class="madp-detail-basic-info-time" v-if="tableType === 'date'">{{ selectedRow.createTime }}</div>
                            <div v-else>{{ selectedRow.name }}</div>
                        </div>
                        <download-btn title="导出Excel" @click="downloadDetailExcel" />
                    </div>
                    <div class="madp-common-mt">
                        <el-table
                            :header-cell-style="{
                                background: 'rgb(255, 191, 191)',
                                color: 'rgb(44,44,44)'
                            }"
                            stripe
                            :data="detailData"
                        >
                            <el-table-column prop="contactName" label="全部客户" align="center"></el-table-column>
                            <el-table-column prop="employeeName" label="所属客服" align="center"></el-table-column>
                            <el-table-column prop="tagsList" label="标签" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.tagsList && scope.row.tagsList.length > 0 ? scope.row.tagsList.toString() : '--' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="statusMsg" label="客户状态" align="center"></el-table-column>
                            <el-table-column prop="createTime" label="添加时间" align="center">
                                <template slot-scope="scope">
                                    <div v-if="scope.row.createTime">
                                        <div>
                                            {{ scope.row.createTime.slice(0, 10) }}
                                        </div>
                                        <div>{{ scope.row.createTime.slice(11) }}</div>
                                    </div>
                                    <div v-else>--</div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="lastTime" label="上次对话时间" align="center">
                                <template slot-scope="scope">
                                    <div v-if="scope.row.lastTime">
                                        <div>
                                            {{ scope.row.lastTime.slice(0, 10) }}
                                        </div>
                                        <div>{{ scope.row.lastTime.slice(11) }}</div>
                                    </div>
                                    <div v-else>--</div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="channel" label="添加渠道" align="center">
                                <template slot-scope="scope">
                                    <div>{{ scope.row.channel || '--' }}</div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="madp-bottom-pagination">
                        <el-pagination
                            background
                            :current-page="detailPage.current"
                            @size-change="handleDetailSizeChange"
                            @current-change="handleDetailCurrentChange"
                            :page-sizes="[10, 20, 30, 50, 100]"
                            :page-size="detailPage.size"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="detailPage.total"
                            style="float: right"
                        ></el-pagination>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="onCloseDetail" type="primary">确定</el-button>
                </div>
            </el-dialog>
        </div>
        <div v-if="isStatisticsCstDetailShow">
            <customer-detail :detailMsg="detailMsg" :backShow="false" :isComponent="true"></customer-detail>
        </div>
    </div>
</template>
<script>
import customerDetail from '@/views/customer/customer-list/detail';
import {
    getChannelBasicInfo,
    getChannelEchartsInfo,
    getChannelInfoByDate,
    downloadChannelInfoByDate,
    getChannelDetailByDate,
    downloadChannelDetailByDate,
    getChannelInfoByStaff,
    downloadChannelInfoByStaff,
    getChannelDetailByStaff,
    downloadChannelDetailByStaff
} from '@/api/customers-of-drainage/statistics';
import { getDepartmentList } from '@/api/common-interface/department';
import { dateFormat } from '@/util/date';
import DownloadBtn from '@/components/download-btn/';
import { downloadFile } from '@/util/util';
import StatisticsCard from '@/components/statistics-card/';
export default {
    props: {
        channelCodeId: {
            type: Number,
            default: () => {
                return null;
            }
        },
        channelCodeName: {
            type: String,
            default: () => {
                return '';
            }
        },
        isStatisticsCstDetailShow: {
            type: Boolean,
            default: false
        }
    },
    components: {
        customerDetail,
        DownloadBtn,
        StatisticsCard
    },
    data() {
        return {
            codeId: '',
            codeName: '',
            basicCstNumInfo: {},
            dimensionType: 1, //维度 客户总数、新增客户数、流失客户数
            dimensionTypeName: '客户总数',
            statisticDimensionTypes: [
                {
                    label: '客户总数',
                    value: 1
                },
                {
                    label: '新增客户数',
                    value: 2
                },
                {
                    label: '流失客户数',
                    value: 3
                }
            ],
            dateType: '', //日期选择
            dateTypes: [
                {
                    type: 0,
                    label: '今日'
                },
                {
                    type: 1,
                    label: '近一周'
                },
                {
                    type: 2,
                    label: '近一个月'
                }
            ],
            dateRangeVal: [],
            employeeId: '',
            employeeList: [], //活码关联的员工列表
            tableType: 'date',
            statisticsTableData: [],
            page: {
                current: 1,
                size: 10,
                total: 1
            },
            //折线图数据
            lineChartOption: {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: 'line' // 默认为直线，可选为:'line' | 'shadow'
                    },
                    formatter: '{b}<br>客户总数: {c}'
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {
                    name: '人数',
                    type: 'value'
                },
                series: [
                    {
                        name: '客户总数',
                        type: 'line',
                        data: [],
                        lineStyle: {
                            color: '#ED5555'
                        },
                        itemStyle: {
                            color: '#ED5555'
                        }
                    }
                ]
            },
            chartData: [],
            searchParams: {},
            selectedRow: {},
            detailPage: {
                current: 1,
                size: 10,
                total: 0
            },
            detailVisible: false,
            detailData: [],
            dimensionDialogType: 1,
            detailMsg: {},
            cardInfo: [
                {
                    label: '今日添加客户数(人)',
                    key: 'newAddContact',
                    color: '#FFD700'
                },
                {
                    label: '今日流失客户数(人)',
                    key: 'newLossContact',
                    color: '#FF8C00'
                },
                {
                    label: '总添加客户数(人)',
                    key: 'allAddContact',
                    color: '#90EE90'
                },
                {
                    label: '总流失客户数(人)',
                    key: 'allLossContact',
                    color: '#00CED1'
                }
            ]
        };
    },
    watch: {
        dateType(newVal, oldVal) {
            if (newVal === '') return;
            let endDate = new Date();
            let startDate = new Date();
            if (newVal === 0) {
                this.dateRangeVal = [startDate, endDate];
            } else if (newVal === 1) {
                startDate.setTime(endDate.getTime() - 3600 * 1000 * 24 * 6);
                this.dateRangeVal = [startDate, endDate];
            } else {
                startDate.setTime(endDate.getTime() - 3600 * 1000 * 24 * 29);
                this.dateRangeVal = [startDate, endDate];
            }
            this.queryDataByParamsChange();
        }
    },
    created() {
        this.codeId = this.channelCodeId;
        this.codeName = this.channelCodeName;
        // dateType默认值为近一周
        this.dateType = 1;
    },
    mounted() {
        this.fetchEmployeeList();
        this.getBasicInfo();
    },
    methods: {
        resetQuery() {
            this.employeeId = '';
            this.dimensionType = 1;
            this.dimensionTypeName = '客户总数';
            if (this.dateType !== 1) {
                this.dateType = 1;
            } else {
                this.queryDataByParamsChange();
            }
        },
        // 顶部基础信息
        getBasicInfo() {
            getChannelBasicInfo({ channelId: this.codeId }).then((res) => {
                if (res.data.code === 0) {
                    this.basicCstNumInfo = res.data.data || {};
                }
            });
        },
        // 成员数据列表
        fetchEmployeeList() {
            getDepartmentList().then((res) => {
                if (res.data && res.data.code === 0) {
                    let data = res.data.data;
                    let { employee } = data;
                    this.employeeList = [{ employeeId: '', name: '请选择' }].concat(employee);
                }
            });
        },
        // 切换图表数据参数
        selectDimensionType(item) {
            this.dimensionType = item.value;
            this.dimensionTypeName = item.label;
            this.queryDataByParamsChange();
        },
        // 日期选择后重置dateType值为""
        resetDateType(val) {
            this.dateType = '';
            this.queryDataByParamsChange();
        },
        // 参数变更，请求echarts图及表格数据
        queryDataByParamsChange() {
            const params = {
                channelId: [this.codeId],
                employeeId: this.employeeId,
                type: this.dimensionType,
                startTime: typeof this.dateRangeVal[0] !== 'string' ? dateFormat(this.dateRangeVal[0]).slice(0, 10) : this.dateRangeVal[0],
                endTime: typeof this.dateRangeVal[1] !== 'string' ? dateFormat(this.dateRangeVal[1]).slice(0, 10) : this.dateRangeVal[1]
            };
            this.page = {
                current: 1,
                size: 10,
                total: 0
            };
            this.searchParams = params;
            getChannelEchartsInfo(params).then((res) => {
                if (res.data.code === 0) {
                    this.chartData = res.data.data || [];
                    this.setEcharts();
                }
            });
            this.getTableData();
        },
        setEcharts() {
            let xAxisData = [];
            let seriesData = [];
            this.chartData.forEach((item, index) => {
                xAxisData.push(item.createTime);
                seriesData.push(item.counts);
            });
            this.lineChartOption.xAxis.data = xAxisData;
            this.lineChartOption.series[0].data = seriesData;
            this.lineChartOption.tooltip.formatter = `{b}<br>${this.dimensionTypeName}: {c}`;

            let echarts = require('echarts');

            // 绘制图表
            this.$nextTick(() => {
                // 基于准备好的dom，初始化echarts实例
                let myChart = echarts.init(document.getElementById('lineChart'));
                myChart.setOption(this.lineChartOption);
            });
        },
        //
        handleSizeChange(size) {
            this.page.size = size;
            this.getTableData();
        },
        //
        handleCurrentChange(current) {
            this.page.current = current;
            this.getTableData();
        },
        // 切换table_type后获取表格数据
        getTableData(type) {
            if (type) {
                this.tableType = type;
            }
            const params = {
                ...this.searchParams,
                current: type ? 1 : this.page.current,
                size: type ? 10 : this.page.size
            };
            let requestUrl = getChannelInfoByDate;
            if (this.tableType === 'staff') {
                requestUrl = getChannelInfoByStaff;
            }
            requestUrl(params).then((res) => {
                if (res.data.code === 0) {
                    this.statisticsTableData = res.data.data.records || [];
                    this.page.total = res.data.data.total;
                }
            });
        },
        //
        handleDetailSizeChange(size) {
            this.detailPage.size = size;
            this.showDetail(this.selectedRow, this.dimensionDialogType, true);
        },
        //
        handleDetailCurrentChange(current) {
            this.detailPage.current = current;
            this.showDetail(this.selectedRow, this.dimensionDialogType, true);
        },
        showDetail(row, type, isPageChange) {
            this.selectedRow = row;
            // 获取详情数据
            const params = {
                ...this.searchParams,
                type: type || 1,
                current: isPageChange ? this.detailPage.current : 1,
                size: isPageChange ? this.detailPage.size : 10
            };
            let requestUrl = '';
            if (this.tableType === 'date') {
                requestUrl = getChannelDetailByDate;
                params.startTime = row.createTime;
                params.endTime = row.createTime;
            } else {
                requestUrl = getChannelDetailByStaff;
                params.employeeId = row.employeeId;
            }
            requestUrl(params).then((res) => {
                if (res.data.code === 0) {
                    this.detailVisible = true;
                    this.detailData = res.data.data.records || [];
                    this.detailPage.total = res.data.data.total;
                }
            });
        },
        // 关闭详情弹框
        onCloseDetail() {
            this.detailVisible = false;
            this.detailPage = {
                current: 1,
                size: 10,
                total: 0
            };
            this.dimensionDialogType = 1;
            this.selectedRow = {};
        },
        downloadExcel() {
            const params = {
                ...this.searchParams,
                type: undefined
            };
            let requestUrl = downloadChannelInfoByDate;
            let mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            if (this.tableType === 'staff') {
                delete params.employeeId;
                requestUrl = downloadChannelInfoByStaff;
                mimeType = 'application/vnd.ms-excel';
            }
            requestUrl(params).then((res) => {
                const fileName = params.startTime + '至' + params.endTime + `${this.tableType === 'date' ? '按日期' : '按客服'}` + '添加客户数据统计';
                downloadFile(res, fileName);
            });
        },
        downloadDetailExcel() {
            const params = {
                ...this.searchParams,
                type: this.dimensionDialogType
            };
            let requestUrl = '';
            let fileNameTime = params.startTime + '至' + params.endTime;
            if (this.tableType === 'date') {
                requestUrl = downloadChannelDetailByDate;
                params.startTime = this.selectedRow.createTime;
                params.endTime = this.selectedRow.createTime;
                fileNameTime = params.startTime;
            } else {
                requestUrl = downloadChannelDetailByStaff;
                params.employeeId = this.selectedRow.employeeId;
            }
            requestUrl(params).then((res) => {
                const fileName = fileNameTime + '日添加的客户详情';
                downloadFile(res, fileName);
            });
        },
        showCstDetail(row) {
            this.detailMsg = JSON.parse(JSON.stringify(row));
            this.$emit('changeDetailShow', true);
        }
    }
};
</script>
<style lang="scss" scoped>
.madp-statistics-data {
    margin-top: 20px;
}
.madp-top-statistics-boxs {
    display: flex;
    align-items: center;
    margin-top: 20px;
}
.madp-top-statistics-box {
    width: 420px;
    height: 118px;
    background: #fbfdff;
    border: 1px solid #cfe8ff;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    position: relative;
    margin-right: 20px;
    .madp-divider {
        width: 1px;
        height: 50px;
        background-color: #f2f2f2;
    }
    .madp-statistics-item {
        width: 48%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .madp-statistics-item-number {
            font-size: 20px;
            font-weight: bold;
        }
    }
}

.madp-horizontal-divider {
    width: 100%;
    height: 4px;
    margin: 20px 0;
    background-color: #f0f2f5;
}
.madp-gap-wrap {
    margin-top: 10px;
    .madp-gap-title {
        font-weight: 500;
        color: #333;
        line-height: 24px;
        font-size: 17px;
    }
    .madp-statistics-tabs {
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .madp-chart-form .el-form-item {
            margin-right: 20px;
            margin-bottom: 0;
        }
        .madp-date-select {
            width: 120px;
        }
        .el-date-editor--daterange.el-input__inner {
            width: 300px;
        }
        /deep/ .el-date-editor .el-range-separator {
            width: 25px !important;
        }
    }
    .madp-statistics-table {
        margin-top: 20px;
    }
}
/deep/ .el-button--primary.is-plain {
    background-color: #fff;
    border-color: #ed5555;
}
.madp-bottom-pagination {
    margin-top: 10px;
}
.madp-detail {
    &-btn {
        &-desc {
            margin-left: 10px;
            color: #999;
        }
    }
    &-basic {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        &-info {
            display: flex;
            align-items: center;
            &-num {
                font-size: 14px;
                font-weight: 600;
                margin-right: 10px;
            }
            &-time {
                padding-left: 10px;
                line-height: 14px;
                font-size: 12px;
                border-left: 1px solid #e6e6e6;
                color: #999;
            }
        }
    }
}
.madp-common-mt {
    margin-top: 20px;
}
</style>
